/*
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-03-21 10:42:15
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-15 16:07:28
 * @FilePath: /XMate-h5/src/store/modules/minutes/minutes.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import {
  fetchAsrStore,
  getOuterFiledPartnerAPI,
  getReport,
  getAnalyzeLatAPI,
  getShareAnalyzeLatAPI,
  getUserkngAPI,
  generateCourseAPI,
  updateCourseStudyStatusAPI,
  getInternalFiledPartnerAPI,
  generateReport,
  getMeetParList
} from "@/services/minutes";
import { getImprovementAPI } from "@/services/study";
import { diffTimeStrToMs, timeAddTS } from "@/utils/timeTool";

import {
  SUCCESS_CODE,
  CONFERENCE_NEED_PASSWORD
} from "@/services/apiErrorCode";
import {
  AsrStore,
  RecordInfo,
  RecordDetailInfo,
  AsrObject,
  SpeechOverview,
  MindMapSummary,
  QuestionsAnsweringSummary,
  TopicLabResult,
  ConversationalSummary,
  UidInfo,
  CustomerRoles,
  ParticipantResult,
  GenerateReportState,
  GenerateStatus,
  InternalPartner
} from "@/types";
import {
  ReportData,
  SalesCounsellingReport
} from "@/types/minutes/report.type";

import { generateSpeechOverview } from "./utils/speechOverview";
import { generateAiAsrList, generateAsrList } from "./utils/asrProcessing";
import { filterAnalysisTargetObj } from "./utils/reportAnalysis";
import { filterCounsellingTargetObj } from "./utils/counsellingReport";
import { getToken, getUserInfo } from "@/utils/auth";
import EventBus from "@/EventBus.js";
import { EventBusEnum } from "@/types";

export const useMinutesStore = defineStore("minutesStore", {
  state: () => ({
    conferenceId: "",
    shareId: "",
    enableAsrOptimize: false,
    asrStore: {} as AsrStore,
    errorMsg: "",
    needPassword: false,
    needLogin: false,
    searchInfo: null,
    recordIndex: 0,
    enableImprovement: false,
    outerFiledPartner: [] as any[],
    internalFiledTemple: [] as any[],
    report: {} as ReportData,
    courseData: {},
    playerTimeStamp: 0 as number,
    generateReportState: {} as GenerateReportState,
    haveReLabel: false,
    meetParList: [] as any[]
  }),

  getters: {
    // 会议记录信息
    recordInfo: (state): RecordInfo => state.asrStore.recordInfo,

    // 当前记录详情
    currentRecordDetailInfo: (state): RecordDetailInfo =>
      state.asrStore.recordInfo?.recordList?.[state.recordIndex],

    // 总时长
    totalDuration: (state): number => {
      return (
        state.asrStore.recordInfo?.recordList?.reduce(
          (pre: number, item: RecordDetailInfo) => (pre += item.duration),
          0
        ) || 0
      );
    },

    // 客户名称
    customerName: (state): string | null => state.asrStore.customerName || null,

    // AI优化过的字幕列表
    aiAsrList: state => {
      return generateAiAsrList(
        state.asrStore.asrRecognition?.AsrParagraphsList || [],
        state.asrStore.asrRecognition?.UidInfo || {},
        state.asrStore.asrUpdatedContent?.CustomerRoles || [],
        state.asrStore.asrUpdatedContent?.InternalPartners || [],
        state.asrStore.asrUpdatedContent?.ParticipantResult || [],
        state.asrStore.recordInfo?.recordList[0]
      );
    },

    // 原始字幕列表
    asrList: (state): AsrObject[] => {
      return generateAsrList(
        state.asrStore.asrRecognition?.AsrParagraphsList || [],
        state.asrStore.asrRecognition?.UidInfo || {},
        state.asrStore.asrUpdatedContent?.CustomerRoles || [],
        state.asrStore.asrUpdatedContent?.InternalPartners || [],
        state.asrStore.asrUpdatedContent?.ParticipantResult || [],
        state.asrStore.recordInfo?.recordList[0]
      );
    },

    // 获取关键词
    keywordLabResults: state =>
      state.asrStore.asrRecognition?.KeywordLabResults || [],

    // 是否为销售会议
    isSalesMeet: (state): boolean => state.asrStore.meetingType === 7,

    // 发言人统计 - 计算属性，基于 asrList 和角色信息生成发言统计
    speechOverviewData(state: any): SpeechOverview[] {
      return generateSpeechOverview(
        state.asrList,
        state.asrStore.asrUpdatedContent?.CustomerRoles || [],
        state.asrStore.asrUpdatedContent?.InternalPartners || []
      );
    },

    // 是否是纪要拥有者
    isOwner: (state): boolean => {

      if (localStorage.getItem("isDebug") === "true") {
        return true;
      }
      const userInfo = getUserInfo();
      return state.asrStore.hostUserId === userInfo?.id;
    },

    // [总结][思维导图]
    mindMapSummary: (state): MindMapSummary[] =>
      state.asrStore.asrRecognition?.MindMapSummary,

    // [总结][问答回顾]
    getQAList: (state): QuestionsAnsweringSummary[] =>
      state.asrStore.asrRecognition?.QuestionsAnsweringSummary || [],

    // [总结][分段摘要]
    getTopicLabResults(state): TopicLabResult[] {
      let startTime = state.recordInfo?.startTime;
      return state.asrStore.asrRecognition?.TopicLabResults.map(v => {
        return {
          ...v,
          beganTime: timeAddTS(startTime, v.bt)
        };
      });
    },
    
    salesPromoteCourseId(state) {
      return state.asrStore.salesPromoteCourseId;
  },

    // [总结][发言人总结]
    getConversationalSummary() {
      return (this.asrStore.asrRecognition.ConversationalSummary || []).map(
        (v: ConversationalSummary) => {
          return {
            ...v,
            name: this.getUserName(v.ui)
          };
        }
      );
    },

    salesAnalysisReports(state) {
      return state.report.salesAnalysisReports;
    },

    customerAttitude() {
      return filterAnalysisTargetObj("客户态度", this.salesAnalysisReports);
    },

    targetSituation() {
      return filterAnalysisTargetObj("会议达成情况", this.salesAnalysisReports);
    },

    todoInfo() {
      return filterAnalysisTargetObj("待办", this.salesAnalysisReports);
    },

    competeInfo() {
      return filterAnalysisTargetObj("竞争情况", this.salesAnalysisReports);
    },

    riskInfo() {
      return filterAnalysisTargetObj("风险项", this.salesAnalysisReports);
    },

    attitudeList() {
      if (!this.customerAttitude) return [];
      // 态度列表
      const estimateList = this.customerAttitude.客户情绪评估;
      if (!estimateList) return [];
      // 反馈列表
      const feedbackList = this.customerAttitude.客户反馈;
      return estimateList.map(v => {
        const items = feedbackList.filter(temp => v.姓名 === temp.姓名) || [];
        let item;
        if (items && items.length > 0) {
          item = items[0];
        }
        const positiveFeedbackList = item?.积极反馈 || [];
        const negativeFeedbackList = item?.消极反馈 || [];
        let positiveBt = 0;
        let negativeBt = 0;
        if (negativeFeedbackList.length > 0) {
          negativeBt = negativeFeedbackList[0].时间戳;
        }
        if (positiveFeedbackList.length > 0) {
          positiveBt = positiveFeedbackList[0].时间戳;
        }
        return {
          name: v.姓名,
          tag: v.整体情绪,
          reson: v.理由,
          negativeBt,
          positiveBt,
          positiveFeedback: positiveFeedbackList.length,
          negativeFeedback: negativeFeedbackList.length
        };
      });
    },

    oldTodoList() {
      let arr = this.asrStore.asrUpdatedContent.Todos || [];
      arr = arr.map(v => {
        return {
          originContent: v.originalWords,
          content: v.todoContent,
          time: v.timestamp,
          executor: v.executor,
          endTime: "",
          done: v.done
        };
      });
      return arr;
    },

    todoList() {
      if (!this.todoInfo) return this.oldTodoList;
      const tempList = this.todoInfo?.待办事项 || [];
      if (tempList.length === 0) return this.oldTodoList;
      return tempList.map(v => {
        return {
          content: v.待办内容,
          endTime: v.截止时间,
          executor: v.执行人,
          time: v.时间戳,
          originContent: v.原话
        };
      });
    },

    riskListInfo() {
      let riskList = this.riskInfo?.风险项 || [];
      let height = riskList.filter(v => v.风险等级 === "高") || [];
      let medium = riskList.filter(v => v.风险等级 === "中") || [];
      let low = riskList.filter(v => v.风险等级 === "低") || [];
      return {
        height,
        medium,
        low
      };
    },

    salesCounsellingReports(): SalesCounsellingReport[] {
      return this.report?.salesCounsellingReports || [];
    },

    salesPerformance() {
      return (
        filterCounsellingTargetObj("销售表现", this.salesCounsellingReports) ||
        []
      );
    },

    targetSource() {
      return this.salesCounsellingReports.find(
        (item: SalesCounsellingReport) => item.systemId === 205
      )?.targetSettings;
    },

    taskTargetSource() {
      return this.salesCounsellingReports.find(
        (item: SalesCounsellingReport) => item.systemId === 206
      )?.targetSettings;
    },

    isLabelAllParticipant() {
      let totalCount = this.speechOverviewData.length;
      return totalCount <= this.labelParticipantCount;
    },

    // 已经标记的发言人个数
    labelParticipantCount(): number {
      if (!this.asrStore.asrUpdatedContent) return 0;
      const { CustomerRoles = null, InternalPartners = null } =
        this.asrStore.asrUpdatedContent;
      return (CustomerRoles?.length || 0) + (InternalPartners?.length || 0);
    },

    courseFlatList() {
      if (!this.courseData) return [];
      let flatList = [];
      this.courseData.chapterList?.forEach(item => {
        if (item.kngList) {
          item.kngList.forEach(kng => {
            flatList.push(kng);
          });
        }
      });
      return flatList;
    },

    // TODO:  计算进度检查一下
    completeProgress() {
      if (this.courseFlatList.length === 0) {
        return 0;
      }
      const flatList = this.courseFlatList;
      // 计算状态为 2 的数量
      const completedCount = flatList.filter(
        (item: any) => item.status === 2
      ).length;
      // 计算进度
      const totalCount = flatList.length;
      const progress =
        totalCount > 0 ? ((completedCount / totalCount) * 100).toFixed(0) : 0;
      return progress;
    },
    // 是否为即时会议，需要绑定客户
    isNeedBindCustomer(): boolean {
      return !(this.asrStore.customerName?.length > 0);
    }

  },

  actions: {
    async fetchAllData() {
      let res;
      try {
        res = await fetchAsrStore(this.conferenceId);
      } catch (error: any) {
        this.needLogin = error.status === 401;
        this.errorMsg = error.message || "请求数据异常";
        return;
      }

      const { data, code, message } = res;

      if (code === CONFERENCE_NEED_PASSWORD) {
        this.needPassword = true;
        this.shareId = data;
        return;
      }
      if (code !== SUCCESS_CODE) {
        this.errorMsg = message;
        return;
      }

      this.asrStore = data;

      this.getReportAction().then(({ status }) => {
        if (status === GenerateStatus.IN_PROCESS) {
          this.checkReportStatusAction();
        }
      });

      if (getToken()) {
        getOuterFiledPartnerAPI().then(v => {
          this.outerFiledPartner = v;
        });
        this.getInternalFiledPartnerAction().then();
      }

      this.getImprovementAction();
    },

    async getImprovementAction() {
      try {
        this.enableImprovement = await getImprovementAPI();
        if (this.enableImprovement) {
          // 获取学习包，获取学习进度
          this.getUserkngAction(this.conferenceId);
        }
      } catch (error) {
        console.log('获取能力提升要素失败 :>> ', error);
      }
    },

    updateRemakeStatus() {
      this.haveReLabel = true;
    },

    async generateReportAction() {
      let confId = this.conferenceId;
      let sentences = this.asrList.map((v) => {
        return {
          content: v.txt,
          startTime: v.startTime,
          username: v.name,
        };
      });
      this.generateReportState.progress = 0;
      this.haveReLabel = false;
      generateReport(confId, { sentences, forceRenew: true });
      this.generateReportState.generateStatus = GenerateStatus.IN_PROCESS;
      this.checkReportStatusAction();

    },

    async getReportAction() {
      const data = await getReport(this.conferenceId);
      const { status, report, complete } = data;
      this.generateReportState = {
        generateStatus: status,
        progress: complete
      };
      if (status === GenerateStatus.SUCCESS) {
        this.report = report;
      }
      return data;
    },

    async getAnalyzeLatAction(methodology = 0) {
      let res = null;
      if (this.shareId) {
        res = await getShareAnalyzeLatAPI(this.shareId, methodology);
      } else {
        res = await getAnalyzeLatAPI(this.conferenceId, methodology);
      }
      return res;
    },

    checkReportStatusAction() {
      const timeId = setInterval(async () => {
        const { status } = await this.getReportAction();
        if (status === GenerateStatus.SUCCESS) {
          clearInterval(timeId);
        }
        if (status === GenerateStatus.FAIL) {
          clearInterval(timeId);
        }
      }, 1000 * 10);
    },

    getSpeakOverview(id: string): SpeechOverview {
      console.log("debug === getSpeakOverview: ", id);
      return this.speechOverviewData?.find(
        (v: SpeechOverview) => v.uid === id
      )!;
    },

    setPlayerTimeStamp(time: number | string) {
      EventBus.emit(EventBusEnum.AUDIO_SEEK, time);
      // if (isRealTime === true) {
      //   const timeStr = time as string;
      //   const startTime = this.recordInfo.startTime;
      //   console.log("startTime:", this.recordInfo.startTime);
      //   const diff = diffTimeStrToMs(timeStr, startTime.split(" ")[1]);
      //   console.log("diff:", diff);
      //   EventBus.emit(EventBusEnum.AUDIO_SEEK, diff);
      // }
    },

    setPlayerTimeStampByRealTime(realTime: string) {
      const startTime = this.recordInfo.startTime;
      const diff = diffTimeStrToMs(realTime, startTime.split(" ")[1]);
      console.log("diff:", diff);
      EventBus.emit(EventBusEnum.AUDIO_SEEK, diff);
    },

    getUserName(ui: string): string {
      const uidInfo: Record<string, UidInfo> =
        this.asrStore.asrRecognition?.UidInfo || {};
      const customerRoles: CustomerRoles[] =
        this.asrStore.asrUpdatedContent?.CustomerRoles || [];
      const internalPartners: InternalPartner[] =
        this.asrStore.asrUpdatedContent?.InternalPartners || [];
      const participantResults: ParticipantResult[] =
        this.asrStore.asrUpdatedContent?.ParticipantResult || [];

      let userName = uidInfo[ui]?.name || "-";
      const customerRole = customerRoles.find(role => role.ui === ui);
      if (customerRole?.name) {
        userName = customerRole.name;
        return userName;
      }

      const internalPartner = internalPartners.find(role => role.ui === ui);
      if (internalPartner?.name) {
        userName = internalPartner.name;
        return userName;
      }

      const participantResult = participantResults.find(
        participant => participant.id === ui
      );
      if (participantResult?.value) {
        userName = participantResult.value;
      }
      return userName;
    },

    // 获取学习包
    async getUserkngAction(conferenceId: string) {
      if (conferenceId) {
        this.conferenceId = conferenceId;
      }
      const res = await getUserkngAPI(conferenceId);
      const { code, data } = res;
      if (code === 0) {
        this.courseData = data;
      }
      return res;
    },

    // 生成学习包
    async generateUserKngAction(confId: string) {
      const res = await generateCourseAPI(confId);
      return res;
    },

    // 更新课件学习状态
    async updateCourseStudyStatusAction(
      packageId: string,
      kngId: string,
      status: string
    ) {
      const res = await updateCourseStudyStatusAPI(packageId, kngId, status);
      this.getUserkngAction(this.conferenceId);
      return res;
    },

    async getInternalFiledPartnerAction() {
      const res = await getInternalFiledPartnerAPI();
      if (res.code === 0) {
        this.internalFiledTemple = res.data;
      }
      return res;
    }
  },

  persist: {
    storage: localStorage,
    pick: ["enableAsrOptimize", "outerFiledPartner"]
  }
});

function onPlayerTimeUpdate(time: number) {
  // 这里同步到store
  useMinutesStore().playerTimeStamp = time;
}
